<template>
    <div class="comment-admin">
        <div class="comment-header">
            <h2>留言管理</h2>
            <div class="filters">
                <el-input v-model="searchKeyword" placeholder="搜索昵称或内容" prefix-icon="Search" clearable
                    @input="handleSearch" />
            </div>
        </div>

        <el-table :data="messages" style="width: 100%" v-loading="loading">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="nickname" label="昵称" width="120" />
            <el-table-column prop="email" label="邮箱" width="180" />
            <el-table-column prop="content" label="留言内容">
                <template #default="{ row }">
                    <div class="message-content">{{ row.content }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="发布时间" width="180">
                <template #default="{ row }">
                    {{ formatTime(row.createTime) }}
                </template>
            </el-table-column>
            <el-table-column prop="likes" label="点赞数" width="100" />
            <el-table-column label="操作" width="220" fixed="right">
                <template #default="{ row }">
                    <el-button type="primary" link @click="showReplies(row)">
                        查看回复
                    </el-button>
                    <el-button type="success" link @click="handleReply(row)">
                        回复
                    </el-button>
                    <el-button type="danger" link @click="handleDelete(row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagination">
            <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :total="total"
                :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>

        <!-- 回复列表弹窗 -->
        <el-dialog v-model="replyDialogVisible" title="回复列表" width="60%">
            <div class="reply-input" v-if="currentMessage">
                <el-input v-model="replyContent" type="textarea" :rows="3" placeholder="请输入回复内容" />
                <el-button type="primary" @click="submitReply" :loading="submitting">
                    发送回复
                </el-button>
            </div>
            <el-divider />
            <el-table :data="currentReplies" style="width: 100%">
                <el-table-column prop="nickname" label="昵称" width="120" />
                <el-table-column prop="email" label="邮箱" width="180" />
                <el-table-column prop="content" label="回复内容" />
                <el-table-column prop="createTime" label="回复时间" width="180">
                    <template #default="{ row }">
                        {{ formatTime(row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="100" fixed="right">
                    <template #default="{ row }">
                        <el-button type="danger" link @click="handleDeleteReply(row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import type { Message, Reply } from '@/types/guestbook'
import { getMessages, deleteMessage, deleteReply, addReply } from '@/api/guestbook'

const messages = ref<Message[]>([])
const loading = ref(false)
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')

const replyDialogVisible = ref(false)
const currentReplies = ref<Reply[]>([])
const replyContent = ref('')
const submitting = ref(false)
const currentMessage = ref<Message | null>(null)

// 格式化时间
const formatTime = (time: string) => {
    return formatDistanceToNow(new Date(time), { addSuffix: true, locale: zhCN })
}

// 加载留言列表
const loadMessages = async () => {
    loading.value = true
    try {
        const res = await getMessages({
            page: page.value,
            pageSize: pageSize.value,
            keyword: searchKeyword.value
        })
        messages.value = res.list
        total.value = res.total
    } catch (error) {
        console.error('加载留言失败:', error)
        ElMessage.error('加载留言失败')
    } finally {
        loading.value = false
    }
}

// 查看回复
const showReplies = (message: Message) => {
    currentMessage.value = message
    currentReplies.value = message.replies || []
    replyDialogVisible.value = true
}

// 处理回复
const handleReply = (message: Message) => {
    currentMessage.value = message
    currentReplies.value = message.replies || []
    replyContent.value = ''
    replyDialogVisible.value = true
}

// 提交回复
const submitReply = async () => {
    if (!currentMessage.value) return
    if (!replyContent.value.trim()) {
        ElMessage.warning('请输入回复内容')
        return
    }

    submitting.value = true
    try {
        const res = await addReply(currentMessage.value.id, {
            content: replyContent.value.trim()
        })

        // 更新当前回复列表
        if (currentMessage.value.replies) {
            currentMessage.value.replies.unshift(res)
            currentReplies.value = currentMessage.value.replies
        } else {
            currentMessage.value.replies = [res]
            currentReplies.value = [res]
        }

        replyContent.value = ''
        ElMessage.success('回复成功')
    } catch (error) {
        console.error('回复失败:', error)
        ElMessage.error('回复失败')
    } finally {
        submitting.value = false
    }
}

// 删除留言
const handleDelete = async (message: Message) => {
    try {
        await ElMessageBox.confirm('确定要删除这条留言吗？', '提示', {
            type: 'warning'
        })
        await deleteMessage(message.id)
        ElMessage.success('删除成功')
        loadMessages()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除留言失败:', error)
            ElMessage.error('删除失败')
        }
    }
}

// 删除回复
const handleDeleteReply = async (reply: Reply) => {
    try {
        await ElMessageBox.confirm('确定要删除这条回复吗？', '提示', {
            type: 'warning'
        })

        // 找到对应的主留言
        const parentMessage = messages.value.find(m => m.replies?.some(r => r.id === reply.id))
        if (!parentMessage) {
            throw new Error('找不到对应的主留言')
        }

        // 调用删除回复API，传入主留言ID和回复ID
        await deleteReply(parentMessage.id, reply.id)
        ElMessage.success('删除成功')

        // 更新界面显示
        if (parentMessage.replies) {
            parentMessage.replies = parentMessage.replies.filter(r => r.id !== reply.id)
            currentReplies.value = parentMessage.replies
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除回复失败:', error)
            ElMessage.error('删除失败')
        }
    }
}

// 搜索
const handleSearch = () => {
    page.value = 1
    loadMessages()
}

// 分页相关
const handleSizeChange = (val: number) => {
    pageSize.value = val
    loadMessages()
}

const handleCurrentChange = (val: number) => {
    page.value = val
    loadMessages()
}

onMounted(() => {
    loadMessages()
})
</script>

<style scoped>
.comment-admin {
    width: 100%;
    height: 100%;
    padding: 20px;
}

.comment-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.filters {
    display: flex;
    gap: 16px;
}

.message-content {
    max-width: 400px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

:deep(.el-dialog__body) {
    padding-top: 20px;
}

.reply-input {
    margin-bottom: 20px;
    display: flex;
    gap: 16px;
    align-items: flex-start;
}

.reply-input .el-input {
    flex: 1;
}
</style>
